package com.example.heizhu.appfuncore;

import android.text.TextUtils;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONObject;

import java.io.File;

import core.android.tools.AK;
import core.android.tools.AKPathUtil;
import okhttp3.Call;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * @作者: XQ
 * @创建时间：16/4/3 下午2:06
 * @类说明: 使用 okhttp上传文件,rx 执行
 */
public class OkUploadFileTool {
    private static String domain = "http://res.renrenweidian.com.cn/";//域名
    private static String keyUrl = domain + "v1/auth";// 每上传一次需要一个新key
    private static String fileServerUrl = domain + "v1/upload/file/save?uptype=0";
    private static OkHttpClient okHttpClient = null;

    private static String getAuthKey() throws Exception {
        String authKey = null;
        Request request = new Request.Builder().url(keyUrl).build();
        Response response = getOkHttpClient().newCall(request).execute();
        if (response.isSuccessful()) {
            String data = response.body().string();
            JSONObject sObj = new JSONObject(data);
            authKey = sObj.getString("key");
        } else {
            throw new NullPointerException("获取上传认证 key 失败!");
        }
        return authKey;
    }

    public static void uploadFile(String path, Observer<String> observer) {
        Observable.just(path)
                .filter(new Func1<String, Boolean>() {
                    @Override
                    public Boolean call(String s) {
                        File loaclFile = new File(s);
                        if (!loaclFile.exists()) {
                            throw new NullPointerException("要上传的文件不存在!");
                        } else {
                            return true;
                        }
                    }
                })
                .map(new Func1<String, String>() {
                    @Override
                    public String call(String s) {
                        File loaclFile = new File(s);
                        String result = null;
                        try {
                            String key = getAuthKey();
                            RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), loaclFile);
                            RequestBody requestBody = new MultipartBody.Builder()
                                    .addPart(Headers.of("Content-Disposition", "form-data;name=\"key\""), RequestBody.create(null, key))
                                    .addPart(Headers.of("Content-Disposition", "form-data;name=\"uploadFileName\";" + "filename=" + loaclFile.getName()), fileBody)
                                    .build();
                            Request request = new Request.Builder()
                                    .url(fileServerUrl)
                                    .post(requestBody)
                                    .build();
                            Response response = getOkHttpClient().newCall(request).execute();
                            if (response.isSuccessful()) {
                                result = response.body().string();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return result;
                    }
                })
                .map(new Func1<String, String>() {
                    @Override
                    public String call(String s) {
                        String serverUrl = "";
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if ("88888".equals(jsonObject.optString("code"))) {
                                JSONObject dataObj = jsonObject.optJSONObject("data");
                                serverUrl = dataObj.optString("path");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return serverUrl;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    public static Observable<String> uploadFileObservable(String path) {
        Observable<String> observable = Observable.just(path)
                .filter(new Func1<String, Boolean>() {
                    @Override
                    public Boolean call(String s) {
                        File loaclFile = new File(s);
                        if (!loaclFile.exists()) {
                            throw new NullPointerException("要上传的文件不存在!");
                        } else {
                            return true;
                        }
                    }
                })
                .map(new Func1<String, String>() {
                    @Override
                    public String call(String s) {
                        File loaclFile = new File(s);
                        String result = null;
                        try {
                            String key = getAuthKey();
                            RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), loaclFile);
                            RequestBody requestBody = new MultipartBody.Builder()
                                    .addPart(Headers.of("Content-Disposition", "form-data;name=\"key\""), RequestBody.create(null, key))
                                    .addPart(Headers.of("Content-Disposition", "form-data;name=\"uploadFileName\";" + "filename=" + loaclFile.getName()), fileBody)
                                    .build();
                            Request request = new Request.Builder()
                                    .url(fileServerUrl)
                                    .post(requestBody)
                                    .build();
                            Response response = getOkHttpClient().newCall(request).execute();
                            if (response.isSuccessful()) {
                                result = response.body().string();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return result;
                    }
                })
                .map(new Func1<String, String>() {
                    @Override
                    public String call(String s) {
                        String serverUrl = "";
                        try {
                            if (!TextUtils.isEmpty(s)) {
                                JSONObject jsonObject = new JSONObject(s);
                                if ("88888".equals(jsonObject.optString("code"))) {
                                    JSONObject dataObj = jsonObject.optJSONObject("data");
                                    serverUrl = dataObj.optString("path");
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return serverUrl;
                    }
                });
        return observable;
    }

    private static OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
            if (AK.debug) {
                HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
                interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                builder.addInterceptor(interceptor);
            }
            okHttpClient = builder.build();
        }
        return okHttpClient;
    }

    public static void okhttpUpload() {
        OkHttpUtils.initClient(getOkHttpClient());
        String url = "http://img.ivsky.com/img/tupian/pic/201607/10/qingxing_feiji.jpg";
        File picFile = new File(AKPathUtil.getInstance().getImageDir().getAbsolutePath() + "/qingxing_feiji.jpg");
        String zcwdfileServerUrl = "http://c.img.zckj.159.net/zcwd/uploadimg.ashx?action=headimg";

        OkHttpUtils.post()
                .addFile("uploadfile", "messenger_01.png", picFile)//
                .url(zcwdfileServerUrl)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void inProgress(float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                        AK.e(progress);
                        AK.e(total);
                    }

                    @Override
                    public void onError(Call call, Exception e, int i) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(String s, int i) {
                        AK.e(s);
                    }
                });
    }
}
